#include "DictionaryStandardParser.h"

#include "UnitsParser.h"
#include "EntryStandardParser.h"

#include <QXmlStreamReader>
#include <QString>

namespace Ipc2581b
{

DictionaryStandardParser::DictionaryStandardParser(
    UnitsParser *&_unitsParser
    , EntryStandardParser *&_entryStandardParser
):    m_unitsParser(_unitsParser)
    , m_entryStandardParser(_entryStandardParser)
{

}

bool DictionaryStandardParser::parse(QXmlStreamReader *reader)
{
    /* Pre */

    m_result.reset(new DictionaryStandard());

    /* Attributes */

    QStringRef data;
    if (reader->attributes().hasAttribute(QStringLiteral("units")))
    {
        data = reader->attributes().value(QStringLiteral("units"));
        if (!m_unitsParser->parse(reader, data))
            return false;
        m_result->units = m_unitsParser->result();
    }
    else
    {
        reader->raiseError(QStringLiteral("units: Attribute is required"));
        return false;
    }

    /* Elements */

    while (reader->readNextStartElement())
    {
        auto name = reader->name();
        if (name == QStringLiteral("EntryStandard"))
        {
            if (!m_entryStandardParser->parse(reader))
                return false;
            auto result = m_entryStandardParser->result();
            m_result->entryStandardList.append(result);
        }
        else
            reader->skipCurrentElement();
    }

    /* Post */

    // TODO: Check multiplicity of elements/attributes

    return true;
}

DictionaryStandard *DictionaryStandardParser::result()
{
    return m_result.take();
}

}